package org.zjt.chapter1.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-19 下午4:45
 * @see
 */
public abstract class AbstractHttpServer {


    public abstract ChannelInitializer<NioSocketChannel> getChannelInitializer();


    public void start(Integer port) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {

            ChannelInitializer<NioSocketChannel> channelInitializer = getChannelInitializer();
            // 同步建立服务连接
            Channel channel = new ServerBootstrap()
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .group(bossGroup, eventExecutors)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(channelInitializer).bind(port).sync().channel();


            // 同步阻塞关闭连接
            channel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            eventExecutors.shutdownGracefully();
        }
    }
}
